<template>
  <view class="login-modal" v-if="show">
    <!-- 头像选择弹框 -->
    <view class="modal-container" v-if="step === 1">
      <view class="modal-content">
        <view class="modal-title">设置头像</view>
        <view class="modal-desc">请选择您的头像</view>
        <button class="modal-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          选择头像
        </button>
      </view>
    </view>

    <!-- 手机号获取弹框 -->
    <view class="modal-container" v-if="step === 2">
      <view class="modal-content">
        <view class="modal-title">绑定手机号</view>
        <view class="modal-desc">为了更好的服务体验，请绑定手机号</view>
        <button class="modal-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
          一键获取手机号
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config/config.js'

export default {
  name: 'login-modal',
  
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  
  data() {
    return {
      step: 1,
      tempUserInfo: {
        openid: '',
        avatarUrl: '',
        nickName: '',
        phone: '',
        integral: 0,
        id:''
      }
    }
  },
  
  methods: {
    // 开始登录流程
    async startLogin() {
      try {
        const loginRes = await this.wxLogin()
        if (!loginRes.code) {
          throw new Error('获取微信登录码失败')
        }

        const result = await this.$http.post(config.api.user.login, {
          code: loginRes.code
        })
        
        if (result.data.code !== 200) {
          throw new Error(result.data.msg || '获取openid失败')
        }

        // 保存token和临时用户信息
        this.tempUserInfo = {
          token: result.data.data.token,
          openid: result.data.data.openid,
          nickName: result.data.data.nickName,
          avatarUrl: result.data.data.avatarUrl,
          phone: result.data.data.phone,
          integral: result.data.data.integral,
          id: result.data.data.id
        }

        uni.setStorageSync('userInfo', JSON.stringify(this.tempUserInfo))
        uni.setStorageSync('token', this.tempUserInfo.token)
        // 判断是否需要设置用户信息
        if (this.tempUserInfo.id) {
          if (!this.tempUserInfo.phone) {
            this.step = 2 // 直接进入手机号绑定步骤
          } else {
            this.loginSuccess() // 已有完整信息，直接登录成功
          }
        } else {
          this.step = 1 // 显示头像选择
        }
      } catch (err) {
        this.handleError(err)
      }
    },

    // 头像选择回调
    async onChooseAvatar(e) {
      try {
        const uploadResult = await this.uploadFile(e.detail.avatarUrl)
        this.tempUserInfo.avatarUrl = uploadResult
        this.showNicknameInput()
      } catch (err) {
        this.handleError(err, '头像设置失败')
      }
    },

    // 显示昵称输入框
    showNicknameInput() {
      uni.showModal({
        title: '设置昵称',
        editable: true,
        placeholderText: '请输入昵称',
        success: async (res) => {
          if (res.confirm && res.content) {
            this.tempUserInfo.nickName = res.content
            await this.saveUserInfo()
          } else {
            uni.showToast({
              title: '请输入昵称',
              icon: 'none'
            })
            setTimeout(() => this.showNicknameInput(), 1500)
          }
        }
      })
    },

    // 获取手机号回调
    async onGetPhoneNumber(e) {
      try {
        if (!e.detail.code) {
          throw new Error('获取手机号失败')
        }

        const result = await this.$http.post(config.api.user.getPhone, {
          code: e.detail.code,
          openid: this.tempUserInfo.openid
        })

        if (result.data.code === 200 || result.data.code === 201) {
          this.tempUserInfo.phone = result.data.data
          this.loginSuccess()
        } else {
          throw new Error(result.data.msg || '获取手机号失败')
        }
      } catch (err) {
        this.handleError(err, '获取手机号失败')
      }
    },

    // 保存用户信息
    async saveUserInfo() {
      try {
        const saveResult = await this.$http.post(config.api.user.saveInfo, {
          nickName: this.tempUserInfo.nickName,
          avatarUrl: this.tempUserInfo.avatarUrl,
          openid: this.tempUserInfo.openid
        })

        if (saveResult.data.code === 200 || saveResult.data.code === 201) {
          this.tempUserInfo.integral = saveResult.data.data.integral
          this.tempUserInfo.id=saveResult.data.data.id
          this.step = 2 // 进入手机号绑定步骤
        } else {
          throw new Error(saveResult.data.msg || '保存用户信息失败')
        }
      } catch (err) {
        this.handleError(err, '保存用户信息失败')
      }
    },

    // 登录成功处理
    loginSuccess() {
      const userInfo = { ...this.tempUserInfo }
      uni.setStorageSync('userInfo', JSON.stringify(userInfo))
      this.$emit('login-success', userInfo)
      this.reset()
    },

    // 重置组件状态
    reset() {
      this.step = 1
      this.tempUserInfo = {
        openid: '',
        avatarUrl: '',
        nickName: '',
        phone: '',
        integral: 0,
        id:''
      }
    },

    // 获取微信登录码
    wxLogin() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject
        })
      })
    },

    // 文件上传
    uploadFile(tempFilePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: config.util.getApiUrl(config.api.user.uploadAvatar),
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data'
          },
          success: (uploadFileRes) => {
            try {
              const response = JSON.parse(uploadFileRes.data)
              if (response.code === 200 || response.code === 201) {
                resolve(response.data)
              } else {
                reject(new Error(response.msg || '上传失败'))
              }
            } catch (err) {
              reject(new Error('解析上传结果失败'))
            }
          },
          fail: (err) => reject(new Error('上传文件失败'))
        })
      })
    },

    // 错误处理
    handleError(err, title = '操作失败') {
      console.error(err)
      uni.showToast({
        title: err.message || title,
        icon: 'none'
      })
    }
  }
}
</script>

<style scoped>
.login-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  border-radius: 12px;
  padding: 30px;
  width: 80%;
  max-width: 300px;
}

.modal-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.modal-desc {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

.modal-btn {
  width: 100%;
  height: 44px;
  line-height: 44px;
  background-color: #000;
  color: #fff;
  border-radius: 22px;
  font-size: 16px;
}
</style> 